<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2020/6/22} {14:09} 
 */

namespace wanghua\general_utility_tools_php\huawei\obs\service;


/**
 * 跨域资源共享
 * 跨域资源共享（CORS）允许Web端的应用程序访问不属于本域的资源。OBS提供接口方便开发者控制跨域访问的权限。
 * Class Cors
 * @package libraries\huawei\obs\service
 */
class Cors extends BaseObs
{
    public $AllowedMethod = [];// 指定允许的跨域请求方法(GET/PUT/DELETE/POST/HEAD)

    public $domains = [];//// 指定允许跨域请求的来源 ['http://www.a.com', 'http://www.b.com']

    /**
     * desc：设置跨域规则
     * author：wh
     * @return array
     */
    function setBucketCors(){
        $resp = $this->obsClient->setBucketCors ( [
            'Bucket' => $this->bucketName,
            'CorsRules' => [
                [
                    'ID' => 'rule1',
                    // 指定允许的跨域请求方法(GET/PUT/DELETE/POST/HEAD)
                    'AllowedMethod' => $this->AllowedMethod,
                    // 指定允许跨域请求的来源
                    'AllowedOrigin' => $this->domains,
                    // 控制在OPTIONS预取指令中Access-Control-Request-Headers头中指定的header是否被允许使用
                    'AllowedHeader' => [ 'x-obs-header'],
                    // 指定允许用户从应用程序中访问的header
                    'ExposeHeader' => ['x-obs-expose-header'],
                    // 指定浏览器对特定资源的预取(OPTIONS)请求返回结果的缓存时间,单位为秒
                    'MaxAgeSeconds' => 60
                ]
            ]
        ] );
        return [
            'RequestId'=>$resp['RequestId'],
        ];
    }

    /**
     * desc：查看跨域规则
     * author：wh
     * @return array
     */
    function getBucketCors(){
        $resp = $this->obsClient->getBucketCors ( [
            'Bucket' => $this->bucketName,
        ] );
        $data = [];
        foreach ( $resp ['CorsRules'] as $index => $rule ) {
            $data[]['ID'] = $rule ['ID'];
            $data[]['MaxAgeSeconds'] = $rule ['MaxAgeSeconds'];
            $data[]['AllowedMethod'] = $rule ['AllowedMethod'];
            $data[]['AllowedOrigin'] = $rule ['AllowedOrigin'];
            $data[]['AllowedHeader'] = $rule ['AllowedHeader'];
            $data[]['ExposeHeader'] = $rule ['ExposeHeader'];
        }
        return $data;
    }

    /**
     * desc：删除跨域规则
     * author：wh
     * @return array
     */
    function deleteBucketCors(){
        $resp = $this->obsClient->deleteBucketCors ( [
            'Bucket' => $this->bucketName,
        ] );
        return [
            'RequestId'=>$resp['RequestId'],
        ];
    }
}